package sqlanalysisgui.editor.scanner;

import java.io.IOException;
import java.io.StringReader;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.List;
import java.util.Map;
import java.util.Vector;

import org.apache.log4j.Logger;
import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.LineStyleEvent;
import org.eclipse.swt.custom.LineStyleListener;
import org.eclipse.swt.custom.StyleRange;
import org.eclipse.swt.graphics.Color;
import org.eclipse.swt.graphics.RGB;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Display;

import sqlanalysisgui.session.SessionInfo;
import sqlanalysisgui.view.model.TableInfo;

public class DataBaseSyntaxLineStyler implements LineStyleListener {
	
	private Logger logger =  Logger.getLogger(this.getClass());
	
	DataBaseSysntaxScanner scanner = new DataBaseSysntaxScanner();

	int[] tokenColors;

	Color[] colors;

	Vector blockComments = new Vector();

	public static final int EOF = -1;

	public static final int EOL = 10;

	public static final int WORD = 0;

	public static final int WHITE = 1;

	public static final int KEY = 2;

	public static final int COMMENT = 3;

	public static final int STRING = 5;

	public static final int OTHER = 6;

	public static final int NUMBER = 7;
	
	public static final int DOUBLE_QUOTATION = 8;
	
	public static final int SINGLE_QUOTATION = 9;
	
	public static final int DATABASE_TABLE = 10;
	
	public static final int LOGICAL_OPERATOR = 11;
	
	public static final int PROGRAM_CODE = 12;
	
	public static final int SEARCH_KEYWORD = 13;

	public static final int MAXIMUM_TOKEN = 14;
	
	private List<Map<String, String>> tableInfos;

	public DataBaseSyntaxLineStyler() {
		initializeColors();
		scanner = new DataBaseSysntaxScanner();
	}
	
	public DataBaseSyntaxLineStyler(List<Map<String, String>> tableInfos) {
		this.tableInfos = tableInfos;
		initializeColors();
		scanner = new DataBaseSysntaxScanner();
	}

	Color getColor(int type) {
		if (type < 0 || type >= tokenColors.length) {
			return null;
		}
		return colors[tokenColors[type]];
	}

	boolean inBlockComment(int start, int end) {
		for (int i = 0; i < blockComments.size(); i++) {
			int[] offsets = (int[]) blockComments.elementAt(i);
			// start of comment in the line
			if ((offsets[0] >= start) && (offsets[0] <= end))
				return true;
			// end of comment in the line
			if ((offsets[1] >= start) && (offsets[1] <= end))
				return true;
			if ((offsets[0] <= start) && (offsets[1] >= end))
				return true;
		}
		return false;
	}

	void initializeColors() {
		Display display = Display.getDefault();
		colors = new Color[] { new Color(display, new RGB(0, 0, 0)), // black
				new Color(display, new RGB(255, 0, 0)), // red	//
				new Color(display, new RGB(0, 255, 0)), // green
				new Color(display, new RGB(0, 0, 255)), // blue
				new Color(display, new RGB(140, 140, 140)), // 주석 색상
				new Color(display, new RGB(0, 0, 0)), // 더블 쿼테이션 색상
				new Color(display, new RGB(93, 93, 93)), // 워드 색상
				new Color(display, new RGB(106, 101, 253)), // 싱클 쿼테이션
				new Color(display, new RGB(237, 0, 203)), // 데이터 베이스 테이블
				new Color(display, new RGB(219, 0, 0)), // 논리 연산자
				new Color(display, new RGB(127, 0, 145)), // 프로그램 코드
				new Color(display, new RGB(255, 255, 255)) // 텍스트검색
		};
		tokenColors = new int[MAXIMUM_TOKEN];
		tokenColors[WORD] = 6;
		tokenColors[WHITE] = 0;
		tokenColors[KEY] = 3;
		tokenColors[COMMENT] = 4;
		tokenColors[STRING] = 2;
		tokenColors[OTHER] = 0;
		tokenColors[NUMBER] = 0;
		tokenColors[DOUBLE_QUOTATION] = 0;
		tokenColors[SINGLE_QUOTATION] = 7;
		tokenColors[DATABASE_TABLE] = 8;
		tokenColors[LOGICAL_OPERATOR] = 9;
		tokenColors[PROGRAM_CODE] = 10;
		tokenColors[SEARCH_KEYWORD] = 11;
	}

	void disposeColors() {
		for (int i = 0; i < colors.length; i++) {
			colors[i].dispose();
		}
	}

	/**
	 * Event.detail line start offset (input) Event.text line text (input)
	 * LineStyleEvent.styles Enumeration of StyleRanges, need to be in order.
	 * (output) LineStyleEvent.background line background color (output)
	 */
	public void lineGetStyle(LineStyleEvent event) {
		Vector styles = new Vector();
		int token;
		StyleRange lastStyle;
		
//		logger.debug("event.lineOffset:" + event.lineOffset);
//		logger.debug("event.getSource():" + event.getSource());
//		logger.debug("event.bulletIndex:" + event.bulletIndex);
//		logger.debug("event.indent:" + event.indent);
//		logger.debug("event.wrapIndent:" + event.wrapIndent);
//		logger.debug("event.ranges:" + event.ranges);
//		logger.debug("event.lineText:" + event.lineText);
		
		// If the line is part of a block comment, create one style for the
		// entire line.
		if (inBlockComment(event.lineOffset,
				event.lineOffset + event.lineText.length())) {
			styles.addElement(new StyleRange(event.lineOffset, event.lineText
					.length(), getColor(COMMENT), null));
			event.styles = new StyleRange[styles.size()];
			styles.copyInto(event.styles);
			return;
		}
		Color defaultFgColor = ((Control) event.widget).getForeground();
		scanner.setRange(event.lineText);
		token = scanner.nextToken();
		while (token != EOF) {
			if (token == OTHER) {
				// do nothing for non-colored tokens
			} else if (token != WHITE) {
				Color color = getColor(token);
				// Only create a style if the token color is different than the
				// widget's default foreground color and the token's style is
				// not
				// bold. Keywords are bolded.
				if ((!color.equals(defaultFgColor)) || (token == KEY)) {
					StyleRange style = new StyleRange(scanner.getStartOffset()
							+ event.lineOffset, scanner.getLength(), color,
							null);
					
					if (token == KEY || token == LOGICAL_OPERATOR || token == DATABASE_TABLE || token == PROGRAM_CODE) {
						style.fontStyle = SWT.BOLD;
					}
					
					if (token == SEARCH_KEYWORD) {
						style.fontStyle = SWT.BOLD;
						style.background = new Color(Display.getDefault(), new RGB(51, 153, 255)) ;
					}
					
					if (styles.isEmpty()) {
						styles.addElement(style);
					} else {
						// Merge similar styles. Doing so will improve
						// performance.
						lastStyle = (StyleRange) styles.lastElement();
						if (lastStyle.similarTo(style)
								&& (lastStyle.start + lastStyle.length == style.start)) {
							lastStyle.length += style.length;
						} else {
							styles.addElement(style);
						}
					}
				}
			} else if ((!styles.isEmpty())
					&& ((lastStyle = (StyleRange) styles.lastElement()).fontStyle == SWT.BOLD)) {
				int start = scanner.getStartOffset() + event.lineOffset;
				lastStyle = (StyleRange) styles.lastElement();
				// A font style of SWT.BOLD implies that the last style
				// represents a java keyword.
				if (lastStyle.start + lastStyle.length == start) {
					// Have the white space take on the style before it to
					// minimize the number of style ranges created and the
					// number of font style changes during rendering.
					lastStyle.length += scanner.getLength();
				}
			}
			token = scanner.nextToken();
		}
		event.styles = new StyleRange[styles.size()];
		styles.copyInto(event.styles);
	}

	public void parseBlockComments(String text) {
		blockComments = new Vector();
		StringReader buffer = new StringReader(text);
		int ch;
		boolean blkComment = false;
		int cnt = 0;
		int[] offsets = new int[2];
		boolean done = false;

		try {
			while (!done) {
				switch (ch = buffer.read()) {
				case -1: {
					if (blkComment) {
						offsets[1] = cnt;
						blockComments.addElement(offsets);
					}
					done = true;
					break;
				}
				case '/': {
					ch = buffer.read();
					if ((ch == '*') && (!blkComment)) {
						offsets = new int[2];
						offsets[0] = cnt;
						blkComment = true;
						cnt++;
					} else {
						cnt++;
					}
					cnt++;
					break;
				}
				case '*': {
					if (blkComment) {
						ch = buffer.read();
						cnt++;
						if (ch == '/') {
							blkComment = false;
							offsets[1] = cnt;
							blockComments.addElement(offsets);
						}
					}
					cnt++;
					break;
				}
				default: {
					cnt++;
					break;
				}
				}
			}
		} catch (IOException e) {
			// ignore errors
		}
	}

	public class DataBaseSysntaxScanner {
		
		private Logger logger =  Logger.getLogger(this.getClass());

		protected Hashtable fgKeys = null;

		protected StringBuffer fBuffer = new StringBuffer();

		protected String fDoc;

		protected int fPos;

		protected int fEnd;

		protected int fStartToken;

		protected boolean fEofSeen = false;

		private String[] dataBaseKeywords = { 
				"ALL", "UNION", "MINUS", "INTERSECT ", "DISTINCT",
				"SELECT", "INSERT", "UPDATE", "DELETE", "MERGE", "CREATE",
				"VALUES", "INTO",
				"SET", 
				"JOIN", "OUTER","INNER","RIGHT","LEFT", "CROSS",
				"FROM", "WHERE", "AND", "OR", "IN", "NOT IN", "LIKE", 
				"ORDER", "GROUP", "HAVING", "BY",  
				"ASC", "DESC",  
				"all", "union", "minus", "intersect ", "distinct",
				"select", "insert", "update", "delete", "merge", "create",
				"values", "into",
				"set", 
				"join", "outer","inner","right","left", "cross",
				"from", "where", "and", "or", "in", "not in", "like", 
				"order", "group", "having", "by",
				"asc", "desc"
				};
		
		private String[] fglogicalOperatorKeywords = { 
				"DO", "WHILE", "FOR", "EACH",
				"CONTINUE", 
				"BREAK",
				"IF", "ELSE",
				"do", "while", "for", "each",
				"continue", 
				"break",
				"if", "else",
				"{", "}",
				">", "<", 
				"=", "==", "!", 
				"+", "++", "-", "--",
				"!"
				};
		public DataBaseSysntaxScanner() {
			initialize();
		}

		/**
		 * Returns the ending location of the current token in the document.
		 */
		public final int getLength() {
			return fPos - fStartToken;
		}

		/**
		 * Initialize the lookup table.
		 */
		void initialize() {
			fgKeys = new Hashtable();
			Integer k = new Integer(KEY);
			for (int i = 0; i < dataBaseKeywords.length; i++){
				fgKeys.put(dataBaseKeywords[i].toLowerCase(), k);
			}
			
			Integer logicalKey = new Integer(LOGICAL_OPERATOR);
			for (int i = 0; i < fglogicalOperatorKeywords.length; i++){
				fgKeys.put(fglogicalOperatorKeywords[i].toLowerCase(), logicalKey);
			}
			
			Integer dbKey = new Integer(DATABASE_TABLE);
			if(tableInfos != null){
				for (Map<String, String>  tableInfo: tableInfos) {
					fgKeys.put(tableInfo.get("TABLE_NAME").toLowerCase(), dbKey);
				}
			}
			
			if(SessionInfo.getSearchKeywrods() != null){
				for (String keyword : SessionInfo.getSearchKeywrods()) {
					fgKeys.put(keyword.toLowerCase(), new Integer(SEARCH_KEYWORD));
				}
			}
		}

		/**
		 * Returns the starting location of the current token in the document.
		 */
		public final int getStartOffset() {
			return fStartToken;
		}

		/**
		 * Returns the next lexical token in the document.
		 */
		public int nextToken() {
			int c;
			fStartToken = fPos;
			while (true) {
				switch (c = read()) {
				case EOF:
					return EOF;
				case '/': // comment
					c = read();
//					System.out.println((char)c);
					if (c == '/') {
						while (true) {
							c = read();
							if ((c == EOF) || (c == EOL)) {
								unread(c);
								return COMMENT;
							}
						}
					} else {
						unread(c);
					}
					return OTHER;
				case '\'': // char const
					character: for (;;) {
						c = read();
						switch (c) {
						case '\'':
							return SINGLE_QUOTATION;
						case EOF:
							unread(c);
							return SINGLE_QUOTATION;
						case '\\':
							c = read();
							break;
						}
					}

/*				case '"': // string
					string: for (;;) {
						c = read();
						switch (c) {
						case '"':
							return DOUBLE_QUOTATION;
						case EOF:
							unread(c);
							return STRING;
						case '\\':
							c = read();
							break;
						}
					}*/

				case '0':
				case '1':
				case '2':
				case '3':
				case '4':
				case '5':
				case '6':
				case '7':
				case '8':
				case '9':
					do {
						c = read();
					} while (Character.isDigit((char) c));
					unread(c);
					return NUMBER;
				case '{':
				case '}':
					return LOGICAL_OPERATOR;
				case '+':
				case '-':
				case '>':
				case '<':
				case '!':
				case '=':
				case '(':
				case ')':
				case '*':
				case '@':
				case ',':
					return OTHER;
				default:
					if (Character.isWhitespace((char) c)) {
						do {
							c = read();
						} while (Character.isWhitespace((char) c));
						unread(c);
						return WHITE;
					}
					char castChar = (char) c;
					if (Character.isJavaIdentifierStart(castChar)) {
						fBuffer.setLength(0);
						do {
							fBuffer.append((char) c);
//							System.out.println((char) c);
							c = read();
						} while (Character.isJavaIdentifierPart((char) c));
						unread(c);
						Integer i = (Integer) fgKeys.get(fBuffer.toString().toLowerCase());
						if (i != null)
							return i.intValue();
						return WORD;
					}
					return OTHER;
				}
			}
		}

		/**
		 * Returns next character.
		 */
		protected int read() {
			if (fPos <= fEnd) {
				return fDoc.charAt(fPos++);
			}
			return EOF;
		}

		public void setRange(String text) {
			fDoc = text;
			fPos = 0;
			fEnd = fDoc.length() - 1;
		}

		protected void unread(int c) {
			if (c != EOF)
				fPos--;
		}
	}

}
